package com.campus.client.view;

import com.campus.client.controller.AdminAccountManagementController;
import com.campus.client.net.ClientConnector;
import com.campus.common.vo.Admin;
import com.campus.common.vo.User;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.util.Callback;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class AdminAccountManagementFrame {
    private AdminAccountManagementController adminController;
    private TableView<Admin> adminTable;
    private MenuBar menuBar;
    private Button backBtn;
    private User user = new User();

    public User getUser() {
        return user;
    }

    public void setUser(String Id, String password, String role) {
        this.user.setId(Id);
        this.user.setPassword(password);
        this.user.setRole(role);
    }

    public void start(Stage primaryStage) throws Exception {
        adminController = new AdminAccountManagementController(new ClientConnector("172.20.10.2", 8888));

        BorderPane root = new BorderPane();
        root.setPadding(new Insets(10));
        root.getStyleClass().add("main-container");

        // 顶部标题栏
        HBox headerBox = new HBox();
        headerBox.getStyleClass().add("header-box");
        headerBox.setAlignment(Pos.CENTER_LEFT);
        headerBox.setPadding(new Insets(10, 15, 10, 15));

        Label titleLabel = new Label("管理员账号管理 - 管理员版");
        titleLabel.getStyleClass().add("header-title");

        Region spacer = new Region();
        HBox.setHgrow(spacer, Priority.ALWAYS);

        // 创建菜单栏
        menuBar = createMenuBar();

        Region buttonSpacer = new Region();
        buttonSpacer.setPrefWidth(10);

        backBtn = createStyledButton("返回");
        backBtn.getStyleClass().add("secondary-button");
        backBtn.setOnAction(e -> back());

        headerBox.getChildren().addAll(titleLabel, spacer, menuBar, buttonSpacer, backBtn);
        root.setTop(headerBox);

        // 内容区域
        VBox contentBox = new VBox();
        contentBox.getStyleClass().add("content-box");
        contentBox.setPadding(new Insets(15));

        // 添加搜索面板
        HBox searchPanel = createSearchPanel();
        contentBox.getChildren().add(searchPanel);

        // 创建表格
        adminTable = new TableView<>();
        adminTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        setupTableColumns();

        // 添加表格到滚动面板
        ScrollPane scrollPane = new ScrollPane(adminTable);
        scrollPane.setFitToWidth(true);
        scrollPane.setFitToHeight(true);
        scrollPane.getStyleClass().add("scroll-pane");

        contentBox.getChildren().add(scrollPane);
        root.setCenter(contentBox);

        // 默认加载所有管理员
        loadAllAdmins();

        Scene scene = new Scene(root, 1200, 700);
        scene.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm());
        primaryStage.setTitle("管理员账号管理 - 管理员版");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    // 创建菜单栏
    private MenuBar createMenuBar() {
        MenuBar menuBar = new MenuBar();
        menuBar.getStyleClass().add("admin-menu-bar");

        Menu viewMenu = new Menu("显示操作");
        MenuItem allAdminsItem = new MenuItem("显示所有管理员");
        allAdminsItem.setOnAction(e -> loadAllAdmins());

        Menu manageMenu = new Menu("管理");
        MenuItem addAdminItem = new MenuItem("新增管理员");
        addAdminItem.setOnAction(e -> showAddAdminDialog());

        viewMenu.getItems().add(allAdminsItem);
        manageMenu.getItems().add(addAdminItem);

        menuBar.getMenus().addAll(viewMenu, manageMenu);
        return menuBar;
    }

    // 创建搜索面板
    private HBox createSearchPanel() {
        HBox searchPanel = new HBox(10);
        searchPanel.setPadding(new Insets(10));
        searchPanel.setAlignment(Pos.CENTER_LEFT);

        TextField searchField = new TextField();
        searchField.setPromptText("输入管理员ID");
        searchField.setPrefWidth(200);

        Button searchButton = createStyledButton("搜索");
        searchButton.setOnAction(e -> {
            String keyword = searchField.getText().trim();
            if (!keyword.isEmpty()) {
                try {
                    List<Admin> adminsById = adminController.searchAdmins(keyword);
                    displaySearchResults(adminsById, keyword);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    showAlert("错误", "搜索失败: " + ex.getMessage(), Alert.AlertType.ERROR);
                }
            }
        });

        Button clearButton = createStyledButton("清除搜索");
        clearButton.setOnAction(e -> {
            searchField.clear();
            loadAllAdmins();
        });

        searchPanel.getChildren().addAll(
                new Label("搜索:"), searchField, searchButton, clearButton
        );

        return searchPanel;
    }

    // 设置表格列
    private void setupTableColumns() {
        // 管理员ID列
        TableColumn<Admin, String> idCol = new TableColumn<>("管理员ID");
        idCol.setCellValueFactory(cellData -> new javafx.beans.property.SimpleStringProperty(cellData.getValue().getAdminId()));
        idCol.setMinWidth(150);

        // 操作列
        TableColumn<Admin, Void> actionCol = new TableColumn<>("操作");
        actionCol.setMinWidth(150);
        actionCol.setCellFactory(new Callback<TableColumn<Admin, Void>, TableCell<Admin, Void>>() {
            @Override
            public TableCell<Admin, Void> call(final TableColumn<Admin, Void> param) {
                return new TableCell<Admin, Void>() {
                    private final Button deleteBtn = createStyledButton("删除");
                    private final HBox pane = new HBox(10, deleteBtn);

                    {
                        pane.setAlignment(Pos.CENTER);
                        deleteBtn.getStyleClass().add("danger-button");

                        deleteBtn.setOnAction(event -> {
                            Admin admin = getTableView().getItems().get(getIndex());
                            Alert confirmAlert = new Alert(Alert.AlertType.CONFIRMATION);
                            confirmAlert.setTitle("确认删除");
                            confirmAlert.setHeaderText("确定要删除管理员 " + admin.getAdminId() + " 吗？");
                            confirmAlert.setContentText("此操作不可恢复。");

                            confirmAlert.showAndWait().ifPresent(response -> {
                                if (response == ButtonType.OK) {
                                    try {
                                        boolean success = adminController.deleteAdmin(admin.getAdminId());
                                        if (success) {
                                            showAlert("成功", "删除管理员成功", Alert.AlertType.INFORMATION);
                                            loadAllAdmins();
                                        } else {
                                            showAlert("失败", "删除管理员失败", Alert.AlertType.ERROR);
                                        }
                                    } catch (Exception ex) {
                                        ex.printStackTrace();
                                        showAlert("错误", "删除失败: " + ex.getMessage(), Alert.AlertType.ERROR);
                                    }
                                }
                            });
                        });
                    }

                    @Override
                    protected void updateItem(Void item, boolean empty) {
                        super.updateItem(item, empty);
                        if (empty) {
                            setGraphic(null);
                        } else {
                            setGraphic(pane);
                        }
                    }
                };
            }
        });

        adminTable.getColumns().addAll(idCol, actionCol);
    }

    // 加载所有管理员
    private void loadAllAdmins() {
        try {
            List<Admin> admins = adminController.getAdmins();
            adminTable.getItems().setAll(admins);
        } catch (Exception e) {
            e.printStackTrace();
            showAlert("错误", "加载管理员数据失败: " + e.getMessage(), Alert.AlertType.ERROR);
        }
    }

    // 显示搜索结果
    private void displaySearchResults(List<Admin> admins, String keyword) {
        adminTable.getItems().setAll(admins);
    }

    // 显示新增管理员对话框
    private void showAddAdminDialog() {
        Dialog<Admin> dialog = new Dialog<>();
        dialog.setTitle("新增管理员");
        dialog.setHeaderText("请输入管理员信息");

        // 设置按钮
        ButtonType addButtonType = new ButtonType("添加", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(addButtonType, ButtonType.CANCEL);

        // 创建表单
        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20, 150, 10, 10));

        TextField adminIdField = new TextField();
        adminIdField.setPromptText("管理员ID");

        grid.add(new Label("管理员ID:"), 0, 0);
        grid.add(adminIdField, 1, 0);

        dialog.getDialogPane().setContent(grid);

        // 转换结果为Admin对象
        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == addButtonType) {
                Admin newAdmin = new Admin();
                newAdmin.setAdminId(adminIdField.getText().trim());
                return newAdmin;
            }
            return null;
        });

        Optional<Admin> result = dialog.showAndWait();
        result.ifPresent(admin -> {
            try {
                boolean success = adminController.addAdmin(admin);
                if(success) {
                    showAlert("添加结果", "添加成功", Alert.AlertType.INFORMATION);
                    loadAllAdmins();
                }
                else{
                    showAlert("添加结果", "添加失败", Alert.AlertType.ERROR);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                showAlert("错误", "添加失败: " + ex.getMessage(), Alert.AlertType.ERROR);
            }
        });
    }

    // 统一按钮创建方法
    private Button createStyledButton(String text) {
        Button button = new Button(text);
        button.getStyleClass().add("styled-button");
        return button;
    }

    // 统一提示对话框
    private void showAlert(String title, String message, Alert.AlertType type) {
        Alert alert = new Alert(type, message, ButtonType.OK);
        alert.setHeaderText(title);
        alert.showAndWait();
    }

    private void back() {
        // 获取当前窗口的Stage
        Stage currentStage = (Stage) backBtn.getScene().getWindow();
        currentStage.close();

        // 这里可以添加返回主界面的逻辑
        // 例如：打开管理员主界面
        try {
            AdminMainFrame adminMain = new AdminMainFrame();
            adminMain.setUser(user.getId(), user.getPassword(), user.getRole());
            adminMain.show(new Stage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}